<template>
	<gui-page ref="guiPage" :customHeader="true">
		<!-- 导航 -->
		<template v-slot:gHeader>
			<nav-bar-custom left-icon="left" :leftType="'1'" @clickLeftBack="clickLeftBack"
				:title="$t('pageTranslation.returnToSP')" @clickRight="clickRight" scanType="1"></nav-bar-custom>
		</template>
		<template v-slot:gBody>
			<view class="barcodeSplitting">
				<!-- 扫描和库位选择模块 -->
				<view class="custom-form-card">
					<uni-collapse v-model="data.value">
						<view class="custom-card-title">
							<text class="title-line"></text>
							{{ $t('hardwareOut.barcodeInformation') }}
						</view>
						<view class="custom-card-itemTwo" style="padding: 20rpx 0;">
							<text class="item-info-title"
								style="width:400rpx;">{{ $t('hardwareOut.materialsDepartment') }}：</text>
							<spChooseBox style="text-align: right;" :candidates="data.peportmentList"
								:placeholder="$t('distributedOut.placeholder')" :isJSON="true" keyName="text"
								v-model="data.department" @noselect="noselect" @select="departmentSelect"></spChooseBox>
						</view>
						<view class="custom-card-itemTwo" style="padding: 20rpx 0;">
							<text class="item-info-title"
								style="padding-right: 40rpx;">{{ $t('hardwareOut.scanMaterialCard') }}</text>
							<uni-easyinput class="uni-mt-5" suffixIcon="scan" v-model="data.scanValue" type="search"
								:placeholder="$t('hardwareOut.pleaseScanMaterial')" @confirm="confirm"
								@iconClick="iconClick"></uni-easyinput>
						</view>
						<view class="custom-card-itemTwo" style="padding: 20rpx 0;">
							<text class="item-info-title">{{ $t('stockManage.purposeWarehouse') }}：</text>
							<input type="text" disabled style="margin: 8rpx 0;text-align: right;" class="gui-form-input"
								v-model="data.warehouseCode" :placeholder="$t('pageTranslation.bringFromMaterial')" />
						</view>
						<view class="custom-card-itemTwo" style="padding: 20rpx 0;">
							<text class="item-info-title">{{ $t('stockManage.purposeSeat') }}：</text>
							<input type="text" disabled style="margin: 8rpx 0;text-align: right;" class="gui-form-input"
								v-model="data.locationCode" :placeholder="$t('pageTranslation.bringFromMaterial')" />
						</view>
						<view class="custom-card-itemTwo" style="padding: 20rpx 0;">
							<text class="item-info-title">{{ $t('materials.remark') }}：</text>
							<input type="text" v-model="data.remark" class="gui-form-input gui-text-right"
								:placeholder="$t('materials.pleaseRemarks')" />
						</view>
						<view class="custom-card-itemTwo" style="padding: 20rpx 0">
							<text class="item-info-title" style="padding-right: 40rpx"> <text class="required-color"
									style="padding-right: 6rpx">*</text>{{ $t('pageTranslation.returnQty') }}</text>
							<uni-easyinput class="uni-mt-5" type="number" disabled v-model="data.allInputNum"
								:placeholder="$t('hardwareOut.pleaseQty')"></uni-easyinput>
							<!-- <view class="card-checkBtn bottomBtn-bgcolor-green" @click="handelSureClick">确定</view> -->
						</view>
					</uni-collapse>
				</view>
				<!-- card模块 -->
				<!-- <scroll-view :show-scrollbar="false" :scroll-y="true" class="scroll"> -->
				<view v-if="data.scanInfo" class="custom-form-card">
					<uni-collapse v-model="data.value">
						<uni-collapse-item titleBorder="none" :show-animation="true">
							<template v-slot:title>
								<view class="custom-card-title">
									<text class="title-line"></text>
									{{ $t('distributedOut.atPresent') }}
								</view>
							</template>
							<view class="content">
								<!-- 新增的料卡 -->
								<view class="custom-card-itemOne">
									<text
										class="item-info-title">{{ $t('hardwareOut.materialCard') }}：</text>{{ data.scanValue }}
								</view>

								<view class="custom-card-itemOne">
									<!-- <view class="card-item-50"> -->
									<text
										class="item-info-title">{{ $t('distributedEnter.materialCode') }}：</text>{{ data.scanInfo.materialCode }}
									<!-- </view> -->
									<!-- <view class="card-item-50">
											<text class="item-info-title">{{$t('distributedEnter.materialName')}}：</text>{{data.scanInfo.materialName}}
										</view> -->
								</view>
								<view class="custom-card-itemOne">
									<text
										class="item-info-title">{{ $t('distributedEnter.materialName') }}：</text>{{ data.scanInfo.materialName }}
								</view>
								<view class="custom-card-itemOne">
									<text
										class="item-info-title">{{ $t('distributedEnter.materialSpec') }}：</text>{{ data.scanInfo.materialSpec||'' }}
								</view>
								<view class="custom-card-itemOne">
									<view class="card-item-50">
										<text
											class="item-info-title">{{ $t('distributedEnter.qty') }}：</text>{{ data.scanInfo.currentQty }}
									</view>
									<view class="card-item-50">
										<text
											class="item-info-title">{{ $t('distributedEnter.uom') }}：</text>{{ data.scanInfo.unit }}
									</view>
								</view>
							</view>
						</uni-collapse-item>
					</uni-collapse>
				</view>
				<!-- </scroll-view> -->
				<!-- 底部确定按钮 -->
				<view class="page-bottom-box">
					<view class="page-bottomBtn bottomBtn-bgcolor-green" @click="handelSubmit">{{ $t('calendar.submit') }}
					</view>
				</view>
			</view>
			<!-- 弹框填写数量 -->
			<uni-popup ref="inputDialog" type="center">
				<view v-if="data.scanInfo" class="input-dialog-box">
					<view class="input-dialog-content">
						<view class="input-dialog-item">
							{{ $t('distributedEnter.materialCode') }}:{{ data.scanInfo.materialCode }}
						</view>
						<view class="input-dialog-item">
							{{ $t('distributedEnter.materialName') }}:{{ data.scanInfo.materialName }}
						</view>
						<view class="input-dialog-item">
							{{ $t('distributedEnter.materialSpec') }}:{{ data.scanInfo.materialSpec || '' }}
						</view>
						<view class="input-dialog-item">
							{{ $t('distributedEnter.uom') }}:{{ data.scanInfo.unit }}
						</view>
						<view class="input-dialog-item">
							{{ $t('JsInternational.ofStock') }}:{{ data.scanInfo.currentQty }}
						</view>
						<view class="input-dialog-item flexclass" style="color: #dd524d">
							<view>{{ $t('pageTranslation.returnQty') }}：</view>
							<view class="input-dialog-item-count">
								<input v-model="data.scanInfo.inputNum" type="number"
									:placeholder="$t('JsInternational.plsReturn')" />
							</view>
						</view>
					</view>
					<view class="input-dialog-footer">
						<view class="input-dialog-button" @click="cancelFn">
							{{ $t('popup.cancel') }}
						</view>
						<view class="input-dialog-button dialog-button-left" @click="confirmFn">
							{{ $t('popup.confirm')}}
						</view>
					</view>
				</view>
			</uni-popup>
		</template>
	</gui-page>
</template>

<script setup>
import { navigate, navigateBack } from '@/utils/routerSkip.js';
import { getDataDictionaryFn, pitchOnFn } from '@/utils/index.js'
import { useStore } from "vuex";
import pdaScan from '@/hooks/pdaScan.js'
import spChooseBox from '@/components/spChooseBox';
import chooseSelect from '@/components/chooseSelect';
import {ref,reactive,onMounted,watch,computed,onUnmounted,toRaw} from 'vue';
import { submitReturnHardwareWarehouse, scanHardwareBarcodeReturn } from '@/api/api.js'
import { basPdaOperationLogFn } from '@/utils/index.js';
import { OPERATION_COMMIT, OPERATION_SCAN } from '@/constant/index.js'
import { onBackPress } from '@dcloudio/uni-app';
import { toFixed4 } from '@/utils/index.js';
//JS国际化引入
import { useI18n } from 'vue-i18n';
const { t } = useI18n();

let store = useStore();
//页面弹框输入数量使用的变量
let inputDialog = ref(null)
const { scan } = pdaScan()
let data = reactive({
	costItem: '',//费用项目
	userName: '',//领料人
	picker: '',//工号
	remark: '',//备注
	allInputNum: null,//总数量
	value: ['0'],
	returnSpScanList: [],//扫描存储数组
	warehouseName: '',// 仓库
	warehouseCode: '', //仓库代码
	scanInfo: undefined, // 当前扫描信息
	locationCode: '',// 库位
	scanValue: '',//扫码信息
	inputNum: null,//数量
	peportmentList: [],//领料人数组
	deportmentCode: '', // 领料部门Code
	department: '', //领料部门
});
components: {
	spChooseBox,
		chooseSelect
}
onMounted(() => {
	// 获取库位
	console.log('开始监听PDA扫码')
	uni.$on('scancodedate', (data) => {
		console.log('获取到的code：' + data.code)
		getCode(data.code, 'pda')
	})
	getInitData()
})
onUnmounted(() => {
	// store.dispatch('hardWare/resetReturnSpScanList')
})

const chooseSelectItem = (e) => {
	data.picker = e.userName

	console.log(data.picker, '-----asdasdasda-------')
}

const getInitData = async () => {
	// 获取领料人数据
	await getDataDictionaryFn('Deportment').then(res=>{
		data.peportmentList = res.data
	})
	let tepSelect1 = pitchOnFn(data.peportmentList)
	if (tepSelect1.length == 0) return
	data.department = tepSelect1[0].text // 默认选中第一个 text
	data.deportmentCode = tepSelect1[0].value  // 默认选中第一个 value
}
const departmentSelect = (e) => {
	data.department = e.text
	data.deportmentCode = e.value
}
const chooseSelectCostItem = (e) => {
	data.costItem = e.Name
}
const noselect = (e) => {
	uni.showToast({ title: t('JsInternational.haveNo'), icon: "none" });
	return
}
// 监听手动赋值
const computeData = () => {
	data.allInputNum = null
	if (!data.scanInfo && data.returnSpScanList.length > 0) {
		data.scanInfo = data.returnSpScanList[0]
	}
	if (data.scanInfo && data.returnSpScanList.length == 0) {
		data.scanInfo = undefined
	}
	data.returnSpScanList.forEach(element => {
		data.allInputNum +=toFixed4( Number(element.inputNum))
	});
}
data.returnSpScanList = computed(() => {
	return store.state.hardWare.returnSpScanList
})
// 监听returnSpScanList变化
watch(() => data.returnSpScanList, () => {
	computeData()
}, {
	immediate: true,
	deep: true
});
//监听当前扫描信息的变化
watch(() => data.scanInfo, (newVal) => {
	if (!newVal) {
		data.warehouseName = ''
		data.locationCode = ''
		data.warehouseCode = ''
		data.inputNum = null
	} else {
		data.warehouseName = newVal.warehouseName
		data.locationCode = newVal.locationCode
		data.warehouseCode = newVal.warehouseCode
	}
}, {
	immediate: true,
	deep: true
});
// 用户调起相机扫码
const iconClick = async (type) => {
	console.log(type)
	if (type === 'suffix') {
		let code = await scan()
		getCode(code, 'scan')
	}
}
// 用户点击键盘上搜索
const confirm = () => {
	getCode(data.scanValue, 'keydown')
}
// 获取code
const getCode = (code, type) => {
	let arr = data.returnSpScanList.filter(x => x.barcode == code)
	if (arr.length > 0) {
		uni.showToast({ title: t('JsInternational.repeatTo'), icon: "none" });
		return
	}
	// if(!data.picker || data.picker.length == 0){
	// 	uni.showToast({ title:t('materials.pleaseWorkNo'), icon: "none" });
	// 	return
	// }
	data.scanValue = code
	let parmes = {
		barcode: code
	}
	scanHardwareBarcodeReturn(parmes).then(res => {
		try {
			let inputParameter = JSON.stringify(parmes)
			let returnParameter = JSON.stringify(res)
			let operationPicture = '返还五金仓'
			let callInterface = res.rquestUrl
			let opertionParmes = {
				inputParameter,
				returnParameter,
				operationPicture,
				callInterface,
				responseCode: res.code,//返回状态
				errorMessage: res.msg,//错误信息
				isPass: res.code == 0 ? 'Y' : 'N',//是否成功 Y N
				operationType: OPERATION_SCAN,
				module:'WMS',
				source: "PDA",
			}
			basPdaOperationLogFn(opertionParmes)
		} catch (error) {
		}
		console.log(res)
		if (res.code == 0) {
			data.scanInfo = res.data
			data.scanInfo = res.data
			data.scanInfo.remark = data.remark
			// data.scanInfo.picker = data.picker
			// data.scanInfo.costItem = data.costItem
			inputDialog.value.open()
		} else {
			uni.showToast({ title: res.msg, icon: "none" });
		}
	})
}
// 扫描条码  弹框的取消按钮
const cancelFn = () => {
	data.scanInfo = undefined
	inputDialog.value.close();
}
//扫描条码  弹框的确定按钮
const confirmFn = () => {
	if (data.scanInfo.inputNum == null) {
		uni.showToast({ title: t('JsInternational.plsReturn'), icon: "none" });
		return
	}
	if (Number(data.scanInfo.inputNum) == 0) {
		uni.showToast({ title: t('JsInternational.qtyCant'), icon: "none" });
		return
	}
	data.scanInfo.deportmentCode = data.deportmentCode //手动把当前部门存到扫码信息里面
	store.dispatch('hardWare/setReturnSpScanList', data.scanInfo)
	uni.showToast({ title: t('JsInternational.dataSaved'), icon: "none" });
	inputDialog.value.close();
}

//提交 确定按钮
const handelSubmit = () => {
	if (!data.returnSpScanList.length) {
		uni.showToast({ title: t('JsInternational.scanInput'), icon: "none" });
		return
	}
	if (data.department.length == 0) {
		uni.showToast({ title: t('JsInternational.chooseDept'), icon: "none" });
		return
	}
	let tepData = toRaw(data.returnSpScanList)
	let wmsBarcodeList = []
	let remarkArr = []
	let pickerArr = []
	let costItemArr = []
	tepData.forEach(x => {
		console.log(x)
		wmsBarcodeList.push({
			id: x.id,
			returnQty: x.inputNum,
			barcode:x.barcode
		})
		if (x.remark.length) {
			remarkArr.push(x.remark)
		}
		// if(x.costItem.length){
		// 	costItemArr.push(x.costItem)
		// }
		// pickerArr.push(x.picker)
	});
	let parmes = {
		// picker:pickerArr.join(','),
		// costItem:costItemArr.join(','),
		remarks: remarkArr.join(',')||data.remark,
		deptCode: data.deportmentCode,
		lstBarcodeItem: wmsBarcodeList
	}
	console.log(parmes)
	// 添加加载框
	uni.showLoading({
		title: 'loading',
		mask: true
	});
	submitReturnHardwareWarehouse(parmes).then(res => {
		console.log(res)
		try {
			let inputParameter = JSON.stringify(parmes)
			let returnParameter = JSON.stringify(res)
			let operationPicture = '返还五金仓'
			let callInterface = res.rquestUrl
			let opertionParmes = {
				inputParameter,
				returnParameter,
				operationPicture,
				callInterface,
				responseCode: res.code,//返回状态
				errorMessage: res.msg,//错误信息
				isPass: res.code == 0 ? 'Y' : 'N',//是否成功 Y N
				operationType: OPERATION_COMMIT,
				module:'WMS',
				source: "PDA",
			}
			basPdaOperationLogFn(opertionParmes)
		} catch (error) {
		}
		if (res.code == 0) {
			//隐藏加载框
			uni.hideLoading();
			//删除已提交的数据
			uni.showToast({ title: t('smashRemoval.submitSuccessfully'), icon: "none" });
			store.dispatch('hardWare/resetReturnSpScanList')
			data.scanInfo = null
			data.scanValue = null
			data.allInputNum = null
			data.userName = ''
			data.remark = ''
			// data.costItem = ''
			// navigateBack()
		} else {
			uni.showToast({ title: res.msg, icon: "none" });
		}
	})
}

//扫描纪录
const clickRight = () => {
	navigate({
		url: '/pages/hardware/hardwareBackRecord'
	})
}
onBackPress((options) => {
	if (options.from == 'backbutton') {
		if (!data.returnSpScanList.length) {
			uni.navigateBack({
				delta: 1
			});
			return true
		} else {
			uni.showModal({
				title: t('smashRemoval.warmPrompt'),
				content: t('materials.unsubmittedDataIn'),
				success: function (res) {
					if (res.confirm) {
						store.dispatch('hardWare/resetReturnSpScanList')
						uni.navigateBack({
							delta: 1
						});
					} else if (res.cancel) {
						console.log('用户点击取消');
					}
				}
			});
		}
		return true;
	}
})
//导航栏左侧返回
const clickLeftBack = () => {
	if (!data.returnSpScanList.length) {
		uni.navigateBack({
			delta: 1
		});
		return
	}
	uni.showModal({
		title: t('smashRemoval.warmPrompt'),
		content: t('materials.unsubmittedDataIn'),
		success: function (res) {
			if (res.confirm) {
				store.dispatch('hardWare/resetReturnSpScanList')
				uni.navigateBack({
					delta: 1
				});
			} else if (res.cancel) {
				console.log('用户点击取消');
			}
		}
	});
}
</script>

<style lang="scss" scoped>
.barcodeSplitting {
	display: flex;
	flex-direction: column;
	height: calc(100vh - 88rpx);
	// height: 100vh;
}

.distributed-head {
	border-bottom-left-radius: 16rpx;
	border-bottom-right-radius: 16rpx;
}

.scroll {
	flex: 1;
	height: 2rpx;
}

.page-bottom-box {
	position: absolute;
	left: 0rpx;
	bottom: 0rpx;
	width: 100%
}
</style>
